package za.co.johanmynhardt.jsf.bean;

import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Logger;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.apache.commons.codec.digest.DigestUtils;
import za.co.johanmynhardt.jee.entity.User;

/**
 * @author johan.mynhardt@thumbtribe.mobi
 * @version 2011.1219
 */
@SessionScoped
@ManagedBean
public class LoginBean implements Serializable {
	private final Logger logger = Logger.getLogger(LoginBean.class.getName());
	private String username;
	private String password;
	private User user;
	
	private String resume;
	
	@PersistenceContext
	private EntityManager entityManager;
	
	public void doLogin(ActionEvent actionEvent) {
		password = DigestUtils.sha256Hex(password);
		logger.info(String.format("Logging in: %s, %s.", username, password));

		try {
			User user = (User) entityManager.createQuery("select u from SiteUser u where u.email = :email and u.password = :password").setParameter("email", username).setParameter("password", password).getSingleResult();
			user.setPassword(null);
			password = null;
			this.user = user;
			if (resume != null) {
				String tmpResume = resume;
				resume = null;
				FacesContext.getCurrentInstance().getExternalContext().redirect(tmpResume.concat(".jsf"));
			}
		} catch (NoResultException e) {
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login Failed", "Username or Password is incorrect."));
		} catch (IOException e) {
			logger.severe("Could not redirect after successful login: " + e.getMessage());
		}
	}

	public void doLogout(ActionEvent actionEvent) {
		logger.finest("Logging user out: " + user.getName() + " " + user.getSurname());
		username = null;
		user = null;
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Logged Out", "Successfully logged out."));
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getResume() {
		return resume;
	}

	public void setResume(String resume) {
		logger.info("Resume after login: " + resume);
		this.resume = resume;
	}
}
